package work.lianbiao;

import work.ListNode;

public class Problem24 {
    public ListNode swapPairs2(ListNode head) {

        ListNode listNode = new ListNode(0, head);
        ListNode ans = listNode;

        Integer length = getLength(head);


        for (int i = 1; i < length; i += 2) {
            listNode.next = head.next;
            head.next = head.next.next;
            listNode.next.next = head;
            listNode = head;
            head = head.next;
        }
        return ans.next;

    }

    public Integer getLength(ListNode head) {
        int sum = 0;
        ListNode myList = head;
        while (myList != null) {
            myList = myList.next;
            sum = sum + 1;
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] b = {1,2,3,4};
        ListNode node = ListNode.listNodeFromArray(b);
        Problem24 problem24 = new Problem24();
        ListNode listNode = problem24.swapPairs(node);
        ListNode.printList(listNode);
    }

    public ListNode swapPairs123(ListNode head) {
        ListNode temp = new ListNode(0, head);
        ListNode ans = temp;
        while (temp.next != null && temp.next.next != null) {
            ListNode pre = temp.next;
            ListNode tail = temp.next.next;
            temp.next = tail;
            pre.next = tail.next;
            tail.next = pre;
            temp = temp.next.next;
        }
        return ans.next;
    }

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode listNode1 = swapPairs(head.next.next);
        ListNode listNode2 = head.next;
        head.next.next = head;
        head.next = listNode1;
        return listNode2;
    }


}